from sqlalchemy.orm import Session
from app.models.user import User
from app.core.security import hash_password, verify_password, create_access_token

def create_user(db: Session, username: str, email: str, password: str):
    hashed_pwd = hash_password(password)
    db_user = User(username=username, email=email, hashed_password=hashed_pwd)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def get_user_by_email(db: Session, email: str):
    return db.query(User).filter(User.email == email).first()

def authenticate_user(db: Session, email: str, password: str, remember: bool = False):
    user = get_user_by_email(db, email)
    if not user:
        return None

    if not verify_password(password, user.hashed_password):
        return None

    access_token = create_access_token(subject=user.id, remember=remember)
    return {"access_token": access_token, "token_type": "bearer"}
